package top.jidanmian.android.iot.ui.device

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import top.jidanmian.android.iot.mqtt.MyMqttConn
import javax.inject.Inject

data class LightViewState(
    val onOff: Boolean = false
)

@HiltViewModel
class LightViewModel @Inject constructor(
    private val myMqttConn: MyMqttConn
) : ViewModel(){
    private val tag : String = "LightViewModel"
    private var _uiState = MutableStateFlow(LightViewState())
    val uiState: StateFlow<LightViewState> = _uiState.asStateFlow()

    fun toggle() {
        _uiState.update{
            _uiState.value.copy(
                onOff = !_uiState.value.onOff
            )
        }

        Log.i(tag, "power state: ${_uiState.value.onOff}")

        viewModelScope.launch {
            if (_uiState.value.onOff) {
                myMqttConn.asyncPublish("shop/light/1/command", "ON")
            } else {
                myMqttConn.asyncPublish("shop/light/1/command", "OFF")
            }
        }
    }

    fun test() {
        myMqttConn.disconnect()
    }
}